// 认证相关的API接口 - 专注于与后端交互
import request from './request';
import { isMockMode, mockBaseURL, realBaseURL } from '../config';

// 导入患者、医生和管理员API
import patientLogin from './patient';
import doctorLogin from './doctor';
import adminLogin from './admin';

/**
 * 模拟模式开关
 * 在开发环境下，设置为true将使用模拟数据
 */
// isMockMode 统一从 ../config 引入，避免重复声明与循环依赖

/**
 * 根据用户类型获取登录接口路径
 * @param {string|number} userType - 用户类型
 * @returns {string} 登录接口路径
 * @private
 */
function getLoginPath(userType) {
  switch (userType) {
    case 'doctor':
    case 1:
      return '/auth/doctor-login';
    case 'admin':
    case 3:
      return '/auth/admin-login';
    case 'patient':
    case 2:
    default:
      return '/auth/login';
  }
}

// 登录相关功能将使用文件下方定义的完整模拟函数

// 微信登录模拟功能将使用文件下方定义的完整模拟函数

// 获取用户信息模拟功能将使用文件下方定义的完整模拟函数

/**
 * 账号密码登录
 * @param {Object} loginInfo - 登录信息对象
 * @param {string} loginInfo.phone - 手机号
 * @param {string} loginInfo.password - 密码
 * @param {string|number} loginInfo.userType - 用户类型
 * @param {Object} [loginInfo.additionalInfo] - 额外信息
 * @param {string} [loginInfo.real_name] - 真实姓名
 * @param {number} [loginInfo.age] - 年龄
 * @param {string|number} [loginInfo.gender] - 性别
 * @param {string} [loginInfo.id_card] - 身份证号
 * @returns {Promise<Object>} 登录结果
 */
export async function loginWithPassword(loginInfo) {
  try {
    // 解构登录信息，包含可能在顶层的用户详细信息
    const { phone, password, userType, additionalInfo, real_name, age, gender, id_card, hospital, department, position, ...userDetails } = loginInfo;
    const endpoint = getLoginPath(userType);
    
    console.log('=======================================');
    console.log('[API] 执行账号密码登录:', { phone, userType, endpoint });
    console.log('[API] 直接传递的个人信息字段:');
    console.log('      - 真实姓名:', real_name);
    console.log('      - 年龄:', age, '(类型:', typeof age, ')');
    console.log('      - 性别:', gender, '(类型:', typeof gender, ')');
    console.log('      - 身份证号:', id_card);
    console.log('      - 医院:', hospital);
    console.log('      - 科室:', department);
    console.log('      - 职位:', position);
    console.log('[API] 其他顶层字段:', Object.keys(userDetails));
    console.log('[API] AdditionalInfo:', additionalInfo);
    console.log('=======================================');
    
    if (isMockMode) {
      console.log('[API] 使用模拟登录模式，传递的完整用户信息:');
      console.log('      - 基础信息:', { phone, userType });
      console.log('      - 个人信息字段:', { real_name, age, gender, id_card, hospital, department, position });
      // 模拟登录时传递所有必要参数，但不强制要求密码
      // 确保字段名与API要求匹配
      const mockData = {
        phone,
        // 优先使用顶层字段，然后是additionalInfo
        real_name: userDetails.realName || userDetails.real_name || (additionalInfo && (additionalInfo.realName || additionalInfo.name || additionalInfo.real_name)) || '',
        ...(additionalInfo || {}),
        ...userDetails
      };
      
      // 移除可能不需要的字段或重命名字段以匹配API
      if (mockData.realName) delete mockData.realName;
      if (mockData.idCard) {
        mockData.id_card = mockData.idCard;
        delete mockData.idCard;
      }
      
      console.log('      - 传递给模拟函数的数据:', mockData);
      return mockLoginWithPassword(mockData, userType);
    }
    
    // 构建符合API要求的请求数据
    const requestData = {
      phone,
      // 直接添加个人信息字段
      real_name: real_name || (userDetails.real_name || (additionalInfo && (additionalInfo.realName || additionalInfo.name || additionalInfo.real_name))),
      age: age !== undefined ? age : (userDetails.age !== undefined ? userDetails.age : (additionalInfo && additionalInfo.age)),
      gender: gender !== undefined ? gender : (userDetails.gender !== undefined ? userDetails.gender : (additionalInfo && additionalInfo.gender)),
      id_card: id_card || (userDetails.id_card || (additionalInfo && (additionalInfo.id_card || additionalInfo.idCard))),
      hospital: hospital || (userDetails.hospital || (additionalInfo && additionalInfo.hospital)),
      department: department || (userDetails.department || (additionalInfo && additionalInfo.department)),
      position: position || (userDetails.position || (additionalInfo && additionalInfo.position)),
      // 根据API要求添加必要字段
    };
    
    console.log('\n[API] 构建的初始请求数据 - 包含个人信息字段:');
    console.log(JSON.stringify(requestData, null, 2));
    
    // 只有管理员或明确提供了密码时才添加密码参数
    if (userType === 'admin' || password) {
      requestData.password = password;
    }
    
    // 字段名映射关系
    const fieldMappings = {
      'realName': 'real_name',
      'idCard': 'id_card',
      'age': 'age',
      'gender': 'gender',
      'hospital': 'hospital',
      'department': 'department',
      'position': 'position'
    };
    
    // 性别映射 - 将字符串'male'/'female'映射为数字
      const genderMapping = {
        'male': 1,
        'female': 2
      };
      
      console.log('\n[API] 开始处理性别字段转换:');
      console.log('[API] 当前性别值:', requestData.gender, '(类型:', typeof requestData.gender, ')');

      // 处理顶层用户详细信息
      Object.keys(fieldMappings).forEach(frontendKey => {
        const backendKey = fieldMappings[frontendKey];
        let value;
        
        // 优先使用顶层字段
        if (userDetails[frontendKey] !== undefined && userDetails[frontendKey] !== '') {
          value = userDetails[frontendKey];
        } else if (userDetails[backendKey] !== undefined && userDetails[backendKey] !== '') {
          // 如果后端名称已存在于顶层，也使用它
          value = userDetails[backendKey];
        }
        
        // 处理获取到的值
        if (value !== undefined && value !== '') {
          // 特殊处理性别字段
      if (frontendKey === 'gender' && value !== undefined) {
        if (typeof value === 'string') {
          console.log('[API] 性别字符串转换: "' + value + '" ->', genderMapping[value.toLowerCase()] !== undefined ? genderMapping[value.toLowerCase()] : '(未转换)');
          value = genderMapping[value.toLowerCase()] || 0;
          console.log(`[API] 性别字段转换: ${userDetails[frontendKey]} -> ${value}`);
        }
        console.log('[API] 转换后性别值:', value, '(类型:', typeof value, ')');
      }
          
          // 特殊处理年龄字段 - 确保是数字类型
      if (frontendKey === 'age' && value !== undefined) {
        console.log('[API] 当前年龄值:', value, '(类型:', typeof value, ')');
        const originalAge = value;
        value = parseInt(value) || 0;
        console.log('[API] 年龄字符串转换: "' + originalAge + '" ->', value);
        console.log(`[API] 年龄字段转换: ${userDetails[frontendKey]} -> ${value}`);
        console.log('[API] 处理后年龄值:', value, '(类型:', typeof value, ')');
      }
          
          requestData[backendKey] = value;
        }
      });
    
    // 处理additionalInfo中的字段（作为后备）
    if (additionalInfo) {
      // 确保real_name字段存在（如果顶层没有提供）
      if (!requestData.real_name && (additionalInfo.realName || additionalInfo.name || additionalInfo.real_name)) {
        requestData.real_name = additionalInfo.realName || additionalInfo.name || additionalInfo.real_name;
      }
      
      // 处理患者特定字段
      if (userType === 'patient') {
        if (!requestData.id_card && additionalInfo.idCard) {
          requestData.id_card = additionalInfo.idCard;
        }
        // 添加年龄和性别（如果存在）
        if (!requestData.age && additionalInfo.age) {
          requestData.age = parseInt(additionalInfo.age) || 0;
          console.log(`[API] 从additionalInfo获取并转换年龄: ${additionalInfo.age} -> ${requestData.age}`);
        }
        if (!requestData.gender && additionalInfo.gender) {
          if (typeof additionalInfo.gender === 'string') {
            requestData.gender = genderMapping[additionalInfo.gender.toLowerCase()] || 0;
            console.log(`[API] 从additionalInfo获取并转换性别: ${additionalInfo.gender} -> ${requestData.gender}`);
          } else {
            requestData.gender = additionalInfo.gender;
          }
        }
      }
      
      // 处理医生特定字段
      if (userType === 'doctor') {
        if (!requestData.hospital && additionalInfo.hospital) requestData.hospital = additionalInfo.hospital;
        if (!requestData.department && additionalInfo.department) requestData.department = additionalInfo.department;
        if (!requestData.position && additionalInfo.position) requestData.position = additionalInfo.position;
        // 添加年龄和性别（如果存在）
        if (!requestData.age && additionalInfo.age) {
          requestData.age = parseInt(additionalInfo.age) || 0;
          console.log(`[API] 从additionalInfo获取并转换年龄: ${additionalInfo.age} -> ${requestData.age}`);
        }
        if (!requestData.gender && additionalInfo.gender) {
          if (typeof additionalInfo.gender === 'string') {
            requestData.gender = genderMapping[additionalInfo.gender.toLowerCase()] || 0;
            console.log(`[API] 从additionalInfo获取并转换性别: ${additionalInfo.gender} -> ${requestData.gender}`);
          } else {
            requestData.gender = additionalInfo.gender;
          }
        }
      }
    }
    
    // 清理空值
    console.log('\n[API] 开始清理空值字段:');
    const keysBeforeClean = Object.keys(requestData);
    Object.keys(requestData).forEach(key => {
      if (requestData[key] === undefined || requestData[key] === '' || requestData[key] === null) {
        console.log('[API] 删除空值字段:', key, '值为:', requestData[key]);
        delete requestData[key];
      }
    });
    console.log('[API] 清理前字段数量:', keysBeforeClean.length, '清理后字段数量:', Object.keys(requestData).length);
    
    // 增强的请求数据日志，显示完整的请求数据结构
    console.log('[API] 清理空值后的请求数据:', JSON.stringify(requestData, null, 2));
    console.log('[API] 请求数据包含的用户字段:', Object.keys(requestData).filter(key => 
      ['real_name', 'phone', 'id_card', 'age', 'gender', 'hospital', 'department', 'position'].includes(key)
    ));
    
    // 增强的请求数据日志，显示完整的请求数据结构
    console.log('\n[API] 最终发送到服务器的请求数据 - 包含完整个人信息:');
    console.log(JSON.stringify(requestData, null, 2));
    console.log('[API] 请求数据包含的用户字段:', Object.keys(requestData).filter(key => 
      ['real_name', 'id_card', 'age', 'gender', 'hospital', 'department', 'position'].includes(key)
    ));
    console.log('=======================================');

    
    // 在发送请求前记录网络请求详情
    console.log(`[API] 准备发送请求到: ${endpoint}`);
    console.log(`[API] 请求方法: POST`);
    console.log('[API] 发送的请求数据(完整):', JSON.stringify(requestData, null, 2));
    
    const response = await request.post(endpoint, requestData);
    
    console.log('[API] 登录响应:', response);
    console.log('[API] 响应状态:', response.status || 'success');
    
    return response;
  } catch (error) {
    console.error('[API] 登录失败:', error.message || error);
    throw new Error(`登录失败: ${error.message || '未知错误'}`);
  }
}

/**
 * 微信登录 - 添加重试机制
 * @param {Object} params - 登录参数对象
 * @param {string} params.code - 微信登录code
 * @param {string} [params.identity] - 用户身份标识 (patient/doctor/admin)
 * @param {Object} [params.user_info] - 用户信息对象
 * @returns {Promise<Object>} 登录结果
 */
export async function wechatLogin(params, retries = 0) {
  try {
    // 参数解构并设置默认值
    const { code, identity = 'patient', user_info = {} } = params || {};
    
    // 参数校验
    if (!code) {
      throw new Error('缺少必要参数: code');
    }
    
    console.log('[API] 执行微信登录参数详情:', JSON.stringify({
      code: code.length > 10 ? code.substring(0, 10) + '...' : code, // 隐藏完整code出于安全考虑
      identity: identity || 'patient'
    }));
    
    // 构造完整的请求数据对象，确保与后端期望格式一致
    const requestData = {
      code,
      identity,
      user_info: {
        ...user_info
      },
      // 可选参数，根据需要添加
      encrypted_data: '',
      iv: ''
    };
    
    console.log('[API] 发送到后端的完整请求数据:', JSON.stringify(requestData));
    
    if (isMockMode) {
      console.log('[Mock] 进入模拟微信登录模式');
      return mockWechatLogin(code, user_info.nickname || '', user_info.avatarUrl || '');
    }
    
    // 尝试调用实际的登录接口
    const response = await request.post('/wechat-login', requestData);
    
    console.log('[API] 微信登录响应状态码:', response.code || response.status);
    console.log('[API] 微信登录响应消息:', response.message || response.msg || '无消息');
    return response;
  } catch (error) {
    console.error(`[API] 微信登录失败(第${retries + 1}次尝试):`, JSON.stringify(error));
    
    // 添加重试逻辑，最多重试2次
    const maxRetries = 2;
    if (retries < maxRetries && 
        error && 
        (error.errMsg && (error.errMsg.includes('network') || 
                          error.errMsg.includes('timeout') ||
                          error.errMsg.includes('certificate')))) {
      
      console.log(`[API] 微信登录将在 ${(retries + 1) * 1000}ms 后重试`);
      await new Promise(resolve => setTimeout(resolve, (retries + 1) * 1000));
      return wechatLogin(params, retries + 1);
    }
    
    // 增强错误信息
    const enhancedError = new Error(
      `微信登录失败: ${error.message || 
      (error.errMsg ? error.errMsg : '未知错误')}`
    );
    enhancedError.originalError = error;
    
    throw enhancedError;
  }
}

/**
 * 获取用户信息
 * @returns {Promise<Object>} 用户信息
 */
export async function getUserInfo() {
  try {
    if (isMockMode) {
      return mockGetUserInfo();
    }
    
    console.log('[API] 获取用户信息请求');
    return await request.get('/auth/user-info');
  } catch (error) {
    console.error('[API] 获取用户信息失败:', error.message || error);
    throw new Error(`获取用户信息失败: ${error.message || '未知错误'}`);
  }
}

/**
 * 更新手机号API
 * @param {string} phone - 新手机号
 * @returns {Promise<Object>} 更新响应结果
 */
export const updatePhone = async (phone) => {
  try {
    // 调用真实API
    if (!isMockMode) {
      console.log('[API] 更新手机号', { phone });
      return await request.post('/auth/update-phone', { phone });
    }
    
    // 模拟API响应
    console.log('[Mock] 模拟更新手机号', { phone });
    return mockUpdatePhone(phone);
  } catch (error) {
    console.error('[API] 更新手机号失败:', error);
    throw new Error(`更新手机号失败: ${error.message || '未知错误'}`);
  }
};

/**
 * 更新用户个人信息API
 * @param {Object} userInfo - 用户信息对象
 * @param {string} [userInfo.real_name] - 真实姓名
 * @param {string} [userInfo.phone] - 手机号
 * @param {string} [userInfo.id_card] - 身份证号
 * @param {number|string} [userInfo.age] - 年龄
 * @param {number|string} [userInfo.gender] - 性别
 * @param {string} [userInfo.hospital] - 医院（医生专用）
 * @param {string} [userInfo.department] - 科室（医生专用）
 * @param {string} [userInfo.position] - 职位（医生专用）
 * @returns {Promise<Object>} 更新响应结果
 */
export const updateUserProfile = async (userInfo) => {
  try {
    // 构造请求数据
    const requestData = { ...userInfo };
    
    // 处理性别字段转换
    if (requestData.gender && typeof requestData.gender === 'string') {
      const genderMapping = { 'male': 1, 'female': 2, '男': 1, '女': 2 };
      requestData.gender = genderMapping[requestData.gender.toLowerCase()] || 0;
    }
    
    // 处理年龄字段
    if (requestData.age && typeof requestData.age === 'string') {
      requestData.age = parseInt(requestData.age) || 0;
    }
    
    // 清理空值
    Object.keys(requestData).forEach(key => {
      if (requestData[key] === undefined || requestData[key] === '' || requestData[key] === null) {
        delete requestData[key];
      }
    });
    
    console.log('[API] 更新用户个人信息请求数据:', JSON.stringify(requestData));
    
    // 调用真实API - 根据需求使用patients接口更新患者信息
    if (!isMockMode) {
      return await request.post('/users/patient', requestData);
    }
    
    // 模拟API响应
    console.log('[Mock] 模拟更新用户个人信息');
    return { success: true, message: '个人信息更新成功' };
  } catch (error) {
    console.error('[API] 更新用户个人信息失败:', error);
    throw new Error(`更新用户个人信息失败: ${error.message || '未知错误'}`);
  }
};

/**
 * 用户类型切换API
 * @param {string} targetType - 目标用户类型
 * @returns {Promise<Object>} 切换响应结果
 */
export const switchUserType = async (targetType) => {
  try {
    // 调用真实API
    if (!isMockMode) {
      console.log('[API] 切换用户类型', { targetType });
      return await request.post('/auth/switch-user-type', { target_type: targetType });
    }
    
    // 模拟API响应
    console.log('[Mock] 模拟切换用户类型', { targetType });
    return mockSwitchUserType(targetType);
  } catch (error) {
    console.error('[API] 切换用户类型失败:', error);
    throw new Error(`切换用户类型失败: ${error.message || '未知错误'}`);
  }
};

/**
 * 发送短信验证码
 * @param {string} phone - 手机号
 * @returns {Promise<Object>} 发送结果
 */
export async function sendSmsCode(phone) {
  try {
    console.log('[API] 发送验证码:', phone);
    
    if (isMockMode) {
      console.log('[Mock] 模拟发送验证码');
      return mockSendSmsCode(phone);
    }
    
    return await request.post('/auth/send-sms', { phone });
  } catch (error) {
    console.error('[API] 发送验证码失败:', error);
    throw new Error(`发送验证码失败: ${error.message || '未知错误'}`);
  }
}

/**
 * 验证码登录
 * @param {string} phone - 手机号
 * @param {string} code - 验证码
 * @returns {Promise<Object>} 登录结果
 */
export async function smsLogin(phone, code) {
  try {
    console.log('[API] 验证码登录:', phone);
    
    if (isMockMode) {
      console.log('[Mock] 模拟验证码登录');
      return mockSmsLogin(phone, code);
    }
    
    return await request.post('/auth/sms-login', { phone, code });
  } catch (error) {
    console.error('[API] 验证码登录失败:', error);
    throw new Error(`验证码登录失败: ${error.message || '未知错误'}`);
  }
}

// ---------------------- 模拟数据生成函数 ----------------------

/**
 * 生成模拟登录响应
 * @private
 */
function mockLoginWithPassword(loginData, userType) {
  // 从loginData中解构参数，使用与API一致的字段名
  const { phone, age, gender, id_card, hospital, department, position, real_name } = loginData || {};
  
  return new Promise((resolve) => {
    setTimeout(() => {
      // 生成模拟用户ID和token
      const userId = Math.floor(Math.random() * 100000); // 数字ID，与API一致
      const mockToken = `mock_token_${userId}_${Date.now()}`;
      
      // 映射用户类型到数字角色值
      const roleMap = {
        patient: 2,
        doctor: 1,
        admin: 3
      };
      const role = roleMap[userType] || 2;
      
      // 构建符合API返回格式的用户信息
      const mockUserInfo = {
        id: userId,
        phone: phone || '13800138000',
        role: role,
        status: 1,
        create_time: new Date().toISOString().replace('T', ' ').substring(0, 19),
        // 添加API所需的其他字段
        real_name: real_name || '测试用户',
        wechat_name: real_name || '测试用户',
        wechat_avatar: 'https://example.com/avatar.png',
        openid: `openid_${userId}`
      };
      
      // 根据用户类型添加特定信息，确保字段名与API一致
      if (userType === 'patient') {
        mockUserInfo.age = parseInt(age) || 30;
        mockUserInfo.gender = gender === 'male' ? 1 : 2;
        mockUserInfo.id_card = id_card || '110101199001011234';
      } else if (userType === 'doctor') {
        mockUserInfo.hospital = hospital || '测试医院';
        mockUserInfo.department = department || '精神心理科';
        mockUserInfo.position = position || '主任医师';
      }
      
      // 模拟登录响应
      const responseData = {
        code: 200,
        msg: '登录成功',
        data: {
          token: mockToken,
          userId: userId,
          role: role,
          user_info: mockUserInfo
        }
      };
      
      console.log('[Mock] 模拟登录响应:', JSON.stringify(responseData, null, 2));
      resolve(responseData);
    }, 500);
  });
}

/**
 * 生成模拟微信登录响应
 * @private
 */
function mockWechatLogin(code, nickname, avatarUrl) {
  return new Promise((resolve) => {
    setTimeout(() => {
      const userId = `wechat_user_${Date.now()}`;
      resolve({
        code: 200,
        msg: '微信登录成功',
        data: {
          token: `mock_wechat_token_${Date.now()}`,
          userId: userId,
          role: 2, // 默认患者角色
          userInfo: {
            id: userId,
            openid: `mock_openid_${Date.now()}`,
            wechat_name: nickname,
            wechat_avatar: avatarUrl,
            nickname: nickname,
            avatar_url: avatarUrl,
            role: 2,
            status: 1,
            create_time: new Date().toISOString().replace('T', ' ').substring(0, 19),
            update_time: new Date().toISOString().replace('T', ' ').substring(0, 19)
          }
        }
      });
    }, 500);
  });
}

/**
 * 生成模拟获取用户信息响应
 * @private
 */
function mockGetUserInfo() {
  return new Promise((resolve) => {
    setTimeout(() => {
      // 从本地存储获取信息，模拟后端数据
      const baseUserInfo = uni.getStorageSync('baseUserInfo') || {};
      const patientInfo = uni.getStorageSync('patientInfo') || {};
      const doctorInfo = uni.getStorageSync('doctorInfo') || {};
      const userType = baseUserInfo.role || 2; // 默认患者类型
      
      // 构建符合后端返回格式的用户信息
      let mockUserInfo = {
        id: baseUserInfo.id || 'mock_user_id',
        openid: baseUserInfo.openid || 'mock_openid',
        wechat_name: baseUserInfo.wechat_name || '测试用户',
        wechat_avatar: baseUserInfo.wechat_avatar || 'https://example.com/avatar.png',
        phone: baseUserInfo.phone || '13800138000',
        role: baseUserInfo.role || userType,
        status: baseUserInfo.status || 1,
        create_time: baseUserInfo.create_time || '2023-01-01 10:00:00',
        update_time: baseUserInfo.update_time || '2023-01-01 10:00:00'
      };
      
      // 根据用户类型添加特定信息
      if (userType === 2) {
        mockUserInfo.gender = patientInfo.gender || 1;
        mockUserInfo.age = patientInfo.age || 30;
        mockUserInfo.id_card = patientInfo.id_card || '110101199001011234';
        mockUserInfo.user_type = 'patient';
      } else if (userType === 1) {
        mockUserInfo.hospital = doctorInfo.hospital || '测试医院';
        mockUserInfo.department = doctorInfo.department || '精神科';
        mockUserInfo.position = doctorInfo.position || '主任医师';
        mockUserInfo.user_type = 'doctor';
      }
      
      resolve({
        code: 200,
        msg: '获取用户信息成功',
        data: mockUserInfo
      });
    }, 300);
  });
}

/**
 * 生成模拟更新手机号响应
 * @private
 */
function mockUpdatePhone(phone) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        code: 200,
        msg: '手机号更新成功',
        data: {
          phone
        }
      });
    }, 300);
  });
}

/**
 * 生成模拟用户类型切换响应
 * @private
 */
function mockSwitchUserType(targetType) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        code: 200,
        msg: '用户类型切换成功',
        data: {
          target_type: targetType
        }
      });
    }, 300);
  });
}

/**
 * 生成模拟发送验证码响应
 * @private
 */
function mockSendSmsCode(phone) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        code: 200,
        msg: '验证码发送成功',
        data: {
          dev_code: '123456',
          expires_in: 300
        }
      });
    }, 500);
  });
}

/**
 * 生成模拟验证码登录响应
 * @private
 */
function mockSmsLogin(phone, code) {
  return new Promise((resolve) => {
    setTimeout(() => {
      // 模拟验证码验证
      if (code !== '123456') {
        resolve({
          code: 400,
          msg: '验证码错误'
        });
        return;
      }
      
      const userId = Math.floor(Math.random() * 100000);
      resolve({
        code: 200,
        msg: '登录成功',
        data: {
          token: `mock_sms_token_${userId}_${Date.now()}`,
          user: {
            id: userId,
            phone: phone,
            wechat_name: '测试用户',
            role: 2
          }
        }
      });
    }, 500);
  });
}